<template>
  <div class="app-container home">
    <!-- 数据统计 -->
    <div class="stats-container">
      <el-row :gutter="30">
        <el-col :span="6">
          <div class="stats-card">
            <span class="stats-label">未开始订单：</span>
            <span class="stats-value">{{ statusCount.notStarted }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stats-card">
            <span class="stats-label">行程中订单数：</span>
            <span class="stats-value">{{ statusCount.continued }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stats-card">
            <span class="stats-label">已完成订单数：</span>
            <span class="stats-value">{{ statusCount.finished }}</span>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <v-chart :option="consultLineOption" style="height: 300px;" />
      </el-col>
      <el-col :span="12">
        <v-chart :option="customerSourcePieOption" style="height: 300px;" />
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <v-chart :option="designerPieOption" style="height: 300px;" />
      </el-col>
      <el-col :span="12">
        <v-chart :option="orderBarOption" style="height: 300px;" />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Vue from 'vue'
import ECharts from 'vue-echarts'
import * as echarts from 'echarts'
import { getPictureData } from '@/api/travel/indexPicture' // 仅用这一个接口

Vue.component('v-chart', ECharts)
export default {
  name: "Index",
  components: { 'v-chart': ECharts },
  data() {
    return {
      version: '3.8.7',
      statusCount: { notStarted: 0, continued: 0, finished: 0 },
      allData: null, // 保存所有接口返回的数据
      refreshTimer: null,
      // 折线图配置
      consultLineOption: {
        title: { text: '客服每月接收咨询数量', left: 'center' },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: [{ name: '咨询数量', type: 'line', data: [], smooth: false }]
      },
      // 客户来源饼图
      customerSourcePieOption: {
        title: { text: '客户来源', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{ name: '来源', type: 'pie', radius: '50%', data: [] }]
      },
      // 定制师订单饼图
      designerPieOption: {
        title: { text: '定制师完成订单占比', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{ name: '完成订单', type: 'pie', radius: '50%', data: [] }]
      },
      // 订单柱状图
      orderBarOption: {
        title: { text: '近12个月订单量统计', left: 'center' },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: [{
          name: '订单量',
          type: 'bar',
          data: [],
          barWidth: '40%',
          itemStyle: { color: '#5793f3', borderRadius: [6, 6, 0, 0] }
        }]
      },
    };
  },
  created() {
    // 初始化时只调用一次接口
    this.fetchAllData();
  },
  mounted() {
    // 定时刷新也只调用一次接口
    this.refreshTimer = setInterval(() => {
      console.log('定时刷新数据...');
      this.fetchAllData();
    }, 300000); // 5分钟刷新一次
  },
  beforeDestroy() {
    if (this.refreshTimer) clearInterval(this.refreshTimer);
  },
  methods: {
    // 统一获取所有数据
    async fetchAllData() {
      try {
        const response = await getPictureData();
        this.allData = response.data; // 保存所有数据到allData

        // 数据获取后，分发给各个图表
        this.updateOrderStatus();
        this.updateClientSourcePie();
        this.updateConsultLine();
        this.updateDesignerPie();
        this.updateOrderBar();

      } catch (error) {
        console.error("获取所有数据失败：", error);
      }
    },

    // 1. 更新订单状态统计
    updateOrderStatus() {
      this.statusCount = this.allData.orderStatusCount || { notStarted: 0, continued: 0, finished: 0 };
    },

    // 2. 更新客户来源饼图
    updateClientSourcePie() {
      const sourceData = this.allData.clientSourceCount || {};
      this.customerSourcePieOption.series[0].data = [
        { value: sourceData.source0 || 0, name: '飞猪' },
        { value: sourceData.source1 || 0, name: '58同城' },
        { value: sourceData.source2 || 0, name: '其他' }
      ];
    },

    // 3. 更新咨询折线图
    updateConsultLine() {
      const consultData = this.allData.monthlyConsultCount || [];
      // 1. 生成近12个月的完整月份数组（格式：YYYY-MM）
      const months = [];
      const today = new Date();
      for (let i = 11; i >= 0; i--) {
        const date = new Date(today.getFullYear(), today.getMonth() - i, 1);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 补0（如8月→08）
        months.push(`${year}-${month}`);
      }

      // 2. 将查询数据转为 { "YYYY-MM": count } 格式
      const dataMap = consultData.reduce((map, item) => {
        map[item.month] = item.count || 0;
        return map;
      }, {});

      // 3. 补全12个月数据（空值填0）
      const xAxisMonths = [];
      const seriesData = [];
      months.forEach(month => {
        xAxisMonths.push(`${month.split('-')[1]}月`); // 显示为“08月”→“8月”
        seriesData.push(dataMap[month] || 0);
      });

      // 4. 更新图表
      this.consultLineOption.xAxis.data = xAxisMonths;
      this.consultLineOption.series[0].data = seriesData;
    },

    // 4. 更新定制师订单饼图（直接使用designerName）
    updateDesignerPie() {
      const designerData = this.allData.designerOrderData || [];
      this.designerPieOption.series[0].data = designerData.map(item => ({
        name: item.designerName || '未知定制师', // 直接使用返回的姓名
        value: item.totalCount || 0
      }));
    },

    // 5. 更新订单柱状图
    updateOrderBar() {
      const orderData = this.allData.monthlyOrderStats || [];
      // 1. 生成近12个月的完整月份数组（同上）
      const months = [];
      const today = new Date();
      for (let i = 11; i >= 0; i--) {
        const date = new Date(today.getFullYear(), today.getMonth() - i, 1);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        months.push(`${year}-${month}`);
      }

      // 2. 转换为 { "YYYY-MM": order_count } 格式
      const dataMap = orderData.reduce((map, item) => {
        map[item.month] = item.order_count || 0;
        return map;
      }, {});

      // 3. 补全12个月数据
      const xAxisMonths = [];
      const seriesData = [];
      months.forEach(month => {
        xAxisMonths.push(`${month.split('-')[1]}月`);
        seriesData.push(dataMap[month] || 0);
      });

      // 4. 更新图表
      this.orderBarOption.xAxis.data = xAxisMonths;
      this.orderBarOption.series[0].data = seriesData;
    },

    goTarget(href) {
      window.open(href, '_blank')
    }
  }
}
</script>

<style scoped lang="scss">
/* 样式部分不变 */
.home {
  .stats-container {
    margin-bottom: 20px;

    .el-row {
      display: flex;
      justify-content: space-around;

      .el-col {
        display: flex;
        justify-content: center;
      }

      .stats-card {
        position: relative;
        border: 1px solid #f0f9ff;
        border-radius: 12px;
        padding: 20px 10px;
        background: linear-gradient(150deg, #f9fcff 0%, #fff 100%);
        width: 100%;
        height: 90px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        box-shadow: 0 4px 16px rgba(135, 206, 250, 0.15);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 6px 20px rgba(135, 206, 250, 0.2);
        }

        &::before {
          content: '';
          position: absolute;
          left: 20px;
          top: 50%;
          transform: translateY(-50%);
          width: 40px;
          height: 40px;
          background: url('~@/assets/icons/svg/旅游订单.svg') no-repeat center;
          background-size: contain;
          opacity: 0.9;
        }

        .stats-label {
          font-size: 20px;
          font-weight: 600;
          color: #4b79a1;
          margin-left: 28px;
        }

        .stats-value {
          font-size: 20px;
          font-weight: 600;
          color: #f27a1a;
          margin-left: 8px;
        }
      }
    }
  }

  .el-row {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-col {
    border-radius: 4px;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
}
</style>
